
package scm;
import java.sql.*;
import javax.swing.*;
import java.util.ArrayList;

public class Akcja
{
    private Connection c = null;
    
    public void wykonaj(int actionId)
    {                
        try
        {
            Class.forName("org.postgresql.Driver");
        }
        catch (ClassNotFoundException cnfe)
        {
            JOptionPane.showMessageDialog(null, cnfe.getMessage());
        }
        try
        {
            c = DriverManager.getConnection("jdbc:postgresql://localhost/template1",
                                    "postgres", "przemek");

            PreparedStatement ps = c.prepareStatement("SELECT name, description, action FROM actions WHERE id = ?");
            ps.setInt(1, actionId);
            ResultSet rs = ps.executeQuery();

            String error = "";

            if (rs.next())
            {                
                String action = rs.getString("action");
                String[] actionSplit = action.split(":");
                if (actionSplit[0].equals("email"))
                {
                    if (actionSplit.length == 2)
                    {
                        String group = actionSplit[1];
                        ArrayList<String> emails = new ArrayList<String>();

                        ps = c.prepareStatement("SELECT e_mail FROM userdata WHERE position = ?");
                        ps.setString(1, group);
                        rs = ps.executeQuery();
                        String test = "";
                        while (rs.next())
                        {
                            //emails.add(rs.getString("e_mail"));
                            //test += rs.getString("e_mail") + " ";

                            Email email = new Email(rs.getString("e_mail"), "Powiadomienie z systemu SCM", "XX");
                            email.send();
                        }



                    }
                    else
                    {
                        error = "Nieprawidłowe argumenty";
                    }
                    // TODO: wyslac email 
                }

            }
            else
            {
            }

            if (error != "")
            {
                JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>" + error + "</FONT></HTML>");
                JOptionPane.showMessageDialog(null,errorFields);
            }
         }
         catch (SQLException se)
         {
             JOptionPane.showMessageDialog(null, se.getMessage());
         }
    }
   
}